<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wuwu <15093565100@163.com>
// +----------------------------------------------------------------------
namespace api\portal\controller;

use api\portal\model\PortalCategoryModel;
use api\portal\model\PortalPostModel;
use cmf\controller\RestUserBaseController;
use api\user\model\MaterialModel as Material;
use api\user\model\TagModel as Tag;
use think\Db;
use think\Validate;
use app\common\model\TemplateGroupModel;
use app\common\model\MytaskModel;
use app\common\model\TemplateAttrModel;
use app\common\model\TemplateCategoryModel;
use app\common\logic\home\Material as LMaterial;
use app\common\model\MaterialClassModel;
use app\common\model\RecordModel;
use app\common\model\AppUserModel;
use app\common\model\RelationStudentModel;
use app\common\logic\home\Relation;

class TemplateController extends RestUserBaseController
{

    /**
     * [模板列表]
     * @Author:   wuwu<15093565100@163.com>
     * @DateTime: 2017-07-17T11:36:51+0800
     * @since:    1.0
     */
    public function index()
    {
        $page = $this->request->param('page');
        if(empty($page)){
            $page=1;
        }
        $pagesize=10;
        $data=db('template')->where(['status'=>1])->page("$page,$pagesize")->select();
        $this->success("请求成功",$data);
    }
    //课题模板详情
    public function progress(){
        $mid=$this->request->param('mid');

        $data=Db::name('classprogress')->where(['mid'=>$mid])->select();
        $list=array();
        foreach($data as $key=>$val){
            $list[$val['progressid']]['content'][]=$val;
            $list[$val['progressid']]['name']=$val['name'];
            
        }

        $this->success("请求成功",$list);
    
    }
    //添加我的课题
    public function addtask(){
        $params = $this->request->param();
        $data = TemplateGroupModel::get($params['group_id']);
        //表头
        if(!empty($data['header'])){
            $header = json_decode($data['header'],true);
            $content = json_decode($header['content'],true);
            foreach($content as $val){
                $data_header[$val] = '';
            }
            $header['content'] = json_encode($data_header);
            $param['header'] = json_encode($header);
        }
        //表尾
        if(!empty($data['footer'])){
            $footer = json_decode($data['footer'],true);
            $content = json_decode($footer['content'],true);
            foreach($content as $val){
                $data_footer[$val] = '';
            }
            $footer['content'] = json_encode($data_footer);
            $param['footer'] = json_encode($footer);
        }
        //分类
        $param['template_category_id'] = $data['category_id'];

        $mid = $data['template_id'];
        $mm=Db::name('template')->where("id=".$mid)->field('name,description')->find();
        $userId=$this->getUserId();
        $progress=Db::name('classprogress')->where(['mid'=>$mid])->select();
        $param['content']=$progress;
        $param['name']=$mm['name'];
        $param['description']=$mm['description'];
        $param['uid']=$userId;
        $param['create_time']=date('Y-m-d H:i:s',time());
        $param['update_time']=date('Y-m-d H:i:s',time());
        $param['t_id'] = $mid;
        $param['group_id'] = $params['group_id'];
        $param['p_category_id'] = $data['p_category_id'];
        $re= Db::name('mytask')->insert($param);

        if($re){
            $this->success('成功');
        }else{
            $this->error('失败');
        }
    }
    //我的课题列表
    public function tasklist(){
        $userId=$this->getUserId();
        $data=Db::name('mytask')->where('uid='.$userId)->field('id,uid,create_time,update_time,name,description')->order('create_time desc')->select();
        
        
        $this->success("请求成功",$data);
    }
    //我的课题列表
    public function tasklists(){
        $userId=$this->getUserId();
        $data_template_cate=  TemplateCategoryModel::all(['level'=>1]);
        foreach ($data_template_cate as $key => $value) {
            $datas =Db::name('mytask')->where('uid='.$userId)->where('p_category_id',$value['category_id'])->field('id,uid,create_time,update_time,name,description,names')->order('id desc')->select()->toArray();
            foreach($datas as $k => $val){
                    $datas[$k]['teacher_info']['realName'] = null;
                    $datas[$k]['teacher_info']['header'] = null;
                    $t_user_id =  RecordModel::where('mytask_id',$val['id'])->value('t_user_id');
                    if(!empty($t_user_id)){
                        $rs = AppUserModel::where('id',$t_user_id)->field('realName,header')->find();
                        if(!empty($rs)){
                             $datas[$k]['teacher_info'] = $rs->toArray();
                        }
                    }  
                    $datas[$k]['create_time'] = date('Y-m-d',strtotime($val['create_time']));
                    //dump($val);       
                     
             
            }
             
            $data[$value['category_id']] = $datas;
        }
        //dump($data);
        $this->success("请求成功",$data);
    }
    //课题详情
    public function gettask(){
        $userId=$this->getUserId();
        $Id=$this->request->param('id');
        $data=Db::name('mytask')->where('id='.$Id)->find();
        $content=json_decode($data['content'],true);
        $list=array();
        foreach($content as $key=>$val){
            $reply=$this->getanser($userId,$Id,$val['id']);
            if(!empty($reply)){
               $val['reply']=$reply; 
            }
           $list['template'][$val['progressid']]['content'][]=$val;
            //$list[$val['progressid']]['name']=$val['name'];
        }
        //子标题
        foreach ($list['template'] as $key => $value) {
            $name = TemplateAttrModel::where('template_id',$value['content'][0]['mid'])->where('progress',$key)->value('name');
            $list['names'][$key] = empty($name) ? '' : $name;
        }

        //标题
        $list['name'] = $data['name'];
        //类型 1 课题 2报告
        $list['type'] = $data['type'];
        //ID
        $list['id'] = $data['id'];
        //表头
        if(!empty($data['header'])){
            $header = json_decode($data['header'],true);
            $list['header'] = json_decode($header['content'],true);
        }
        //表尾
        if(!empty($data['footer'])){
            $footer = json_decode($data['footer'],true);
            $list['footer'] = json_decode($footer['content'],true);
        }
         $this->success("请求成功",$list);
        
    }
    /**
     * 保存表头表尾内容
     * @param [type] $[id] [我的课题ID]
     * @param [type] $[name] [填写字段]
     * @param [type] $[answer] [对应回复]
     * @param [type] $[status] [对应状态 header表头 footer表尾]
     * @return [type] [description]
     */
    public function saveHeader(Relation $Relation){
    	$param = $this->request->param();
        $userId=$this->getUserId();
        $mytask_ids = $Relation->getGrouplist($param['id'],$userId);
        if($mytask_ids == 0){
            switch ($param['status']) {
                case 'header':
                    $header = MytaskModel::where('id',$param['id'])->value('header');
                    if(!empty($header)){
                        $header = json_decode($header,true);
                        $content = json_decode($header['content'],true);
                        foreach($content as $key => $val){
                            if($key == $param['name']){
                                $content[$key] = $param['answer'];
                            }
                        }
                        $header['content'] = json_encode($content);
                        $header = json_encode($header);
                        $rs = MytaskModel::where('id',$param['id'])->update(['header'=>$header]);
                    }
                    break;
                case 'footer':
                    $footer = MytaskModel::where('id',$param['id'])->value('footer');
                    if(!empty($footer)){
                        $footer = json_decode($footer,true);
                        $content = json_decode($footer['content'],true);
                        foreach($content as $key => $val){
                            if($key == $param['name']){
                                $content[$key] = $param['answer'];
                            }
                        }
                        $footer['content'] = json_encode($content);
                        $footer = json_encode($footer);
                        $rs = MytaskModel::where('id',$param['id'])->update(['footer'=>$footer]);
                    }
                    break;
            }
        }else{
             switch ($param['status']) {
                case 'header':
                    foreach ($mytask_ids as $key => $value) {
                        $header = MytaskModel::where('id',$value)->value('header');
                        if(!empty($header)){
                            $header = json_decode($header,true);
                            $content = json_decode($header['content'],true);
                            foreach($content as $key => $val){
                                if($key == $param['name']){
                                    $content[$key] = $param['answer'];
                                }
                            }
                            $header['content'] = json_encode($content);
                            $header = json_encode($header);
                            $rs = MytaskModel::where('id',$value)->update(['header'=>$header]);
                        }
                    }
                    
                    break;
                case 'footer':
                    foreach ($mytask_ids as $key => $value) {
                        $footer = MytaskModel::where('id',$value)->value('footer');
                        if(!empty($footer)){
                            $footer = json_decode($footer,true);
                            $content = json_decode($footer['content'],true);
                            foreach($content as $key => $val){
                                if($key == $param['name']){
                                    $content[$key] = $param['answer'];
                                }
                            }
                            $footer['content'] = json_encode($content);
                            $footer = json_encode($footer);
                            $rs = MytaskModel::where('id',$value)->update(['footer'=>$footer]);
                        }
                    }
                    break;
            }
        }
    	
    	if($rs){
    		$this->success('保存成功!');
    	}else{
    		$this->error('保存失败!');
    	}
    }

    //获取课题状态
    function get_task_status(){
        $userId=$this->getUserId();
        $Id=$this->request->param('id');
        $status = Db::name('mytask')->where('id',$Id)->value('status');
        $this->success('',$status);

    }
    /**
     * [回答问题]
     * @param [type] $[content] [<编辑的内容>]
     * @param [type] $[taskid] [<课题ID>]
     * @param [type] $[pid] [<过程ID>]
     * @param [type] $[classprogressid] [<步骤内ID>]
     * @param [type] $[activation_num] [<使用素材数>]
     * @param [type] $[status] [<0 保存>]
     * @return [type] [description]
     */
    public function anser(Relation $Relation){
        $userId=$this->getUserId();
        $param=$this->request->param();
        $mytask_ids = $Relation->getGrouplist($param['taskid'],$userId);

        $info=Db::name('anser')->where(['userId'=>$userId,'taskid'=>$param['taskid'],'pid'=>$param['pid'],'classprogressid'=>$param['classprogressid']])->find();
        if($mytask_ids == 0){
            if($info){
                $param['activation_num']=$param['activation_num']+$info['activation_num'];
                $re=Db::name('anser')->where(['userId'=>$userId,'taskid'=>$param['taskid'],'pid'=>$param['pid'],'classprogressid'=>$param['classprogressid']])->update($param);
            }else{
                $param['userId']=$userId;
                $param['createTime']=date('Y-m-d h:i:s',time());
                $re=Db::name('anser')->insert($param);
            }
        }else{
            if($info){
                $param['activation_num']=$param['activation_num']+$info['activation_num'];
                foreach ($mytask_ids as $key => $value) {
                    $param['taskid'] = $value;
                    $userId = $key;
                    $re=Db::name('anser')->where(['userId'=>$userId,'taskid'=>$param['taskid'],'pid'=>$param['pid'],'classprogressid'=>$param['classprogressid']])->update($param);
                }
                
         
            }else{
                foreach ($mytask_ids as $key => $value) {
                    $param['userId']=$key;
                    $param['taskid'] = $value;
                    $param['createTime']=date('Y-m-d h:i:s',time());
                    $re=Db::name('anser')->insert($param);
                }
               
            }
        }
        
        if($re){
            $this->success('保存成功');
        }else{
            $this->error('保存失败');
        }
    }
    /**
     * [编辑全部小组成员模板]
     * @param [type] $[content] [<编辑的内容>]
     * @param [type] $[taskid] [<课题ID>]
     * @param [type] $[pid] [<过程ID>]
     * @param [type] $[classprogressid] [<步骤内ID>]
     * @param [type] $[activation_num] [<使用素材数>]
     * @param [type] $[status] [<0 保存>]
     * @return [type] [description]
     */
    public function anserGroup11(Relation $Relation){
        $userId=$this->getUserId();

        $param = $this->request->param();

        $mytask_ids = $Relation->getGrouplist($param['taskid'],$userId);

        //$mytask_ids_s = implode(',',$mytask_ids);
        //判断是新增还是修改
        $info=Db::name('anser')->where(['userId'=>$userId,'taskid'=>$param['taskid'],'pid'=>$param['pid'],'classprogressid'=>$param['classprogressid']])->find();

        if($info){
            $param['activation_num']=$param['activation_num']+$info['activation_num'];
            foreach ($mytask_ids as $key => $value) {
                $param['taskid'] = $value;
                $userId = $key;
                $re=Db::name('anser')->where(['userId'=>$userId,'taskid'=>$param['taskid'],'pid'=>$param['pid'],'classprogressid'=>$param['classprogressid']])->update($param);
            }
            
     
        }else{
            foreach ($mytask_ids as $key => $value) {
                $param['userId']=$key;
                $param['taskid'] = $value;
                $param['createTime']=date('Y-m-d h:i:s',time());
                $re=Db::name('anser')->insert($param);
            }
           
        }
        if($re){
            $this->success('保存成功');
        }else{
            $this->error('保存失败');
        }
    }
    public function getanser($userId,$taskid,$pid){
            $param['userId']=$userId;
            $param['taskid']=$taskid;
            $param['classprogressid']=$pid;
            $data=Db::name('anser')->where($param)->order("pid asc,classprogressid asc")->select()->toArray();
            if(empty($data)){
                $data=array();
            }
            return $data;
    }
    public function getoneanser(){
            $userId=$this->getUserId();
            $param=$this->request->param();
            $param['userId']=$userId;
            // $param['userId']=1440;
            // $param['taskid']=17;
            // $param['classprogressid']=2;
            $data=Db::name('anser')->where($param)->find();
            $this->success('请求成功',$data);
            
    }
    //获取问题详情
    public function getquestion(){
       
       $where['id']=$this->request->param('id');
        $pid=$this->request->param('pid',3);
        $content=Db::name('mytask')->where($where)->field('content')->find()['content'];
        $data=json_decode($content);
       
         $this->success("请求成功",$data[$pid]);
    }
    public function get_material_list(Material $Material,Tag $Tag){
        $userId       = $this->getUserId();
       
        $param = $this->request->param();
        $type = $this->request->param('type');
        //类型
       
        if($type==3){
            $where['m.format']=['in','3,4'];
        }else{
             $where['m.format'] = $type;
        }

        $where['m.userId'] = $userId;
        $whereOr='';
        $sort = 'm.createTime desc';
        
        
        $data = $Material->getList($where,$whereOr,$sort,$param);
       
        foreach ($data as $key => $value) {
            if($value['images'] !=''){
                $data[$key]['imgs'] = explode(',', $value['images']);
            }
            if($value['video'] !=''){
                $data[$key]['videos'] = explode(',', $value['video']);
            }
            if($value['audio'] !=''){
                $data[$key]['audios'] = explode(',', $value['audio']);
            }
            if($value['voice'] !=''){
                $data[$key]['voices'] = explode(',', $value['voice']);
            }
            $date = substr($value['createTime'], 0,10);

            $time = substr($value['createTime'], -8);

            $city = mb_substr($value['city'],0, mb_strlen($value['city'])-1);
           // var_dump($date);
            $data[$key]['date'] = explode('-',$date);
            $data[$key]['time'] = explode(':',$time);
            $data[$key]['city'] = $city;
            if($value['city'] !=''){
                $data[$key]['adr'] = $city." ".$value['address'];
            }else{
                $data[$key]['adr'] = $value['address'];
            }
            
        }
        $this->success('',$data);
    }
    public function get_material_list1(Material $Material,Tag $Tag,LMaterial $LMaterial){
        $param = $this->request->param();
        $userId       = $this->getUserId();
        $type = $this->request->param('type');

        //获取小组成员
        $data = $LMaterial->group($param['mytask_id'],$this->userId);
        
        if(!empty($data)){
            //组员集合
            $array1 = [];//全部组员
            $array = [];//抛去自己的所有组员
            foreach($data as $key => $value){
                $array1[] = $value['user_id'];
                if($this->userId != $value['user_id']){
                    $array[] = $value['user_id'];
                }
            }
            
            $user_ids1 = implode(',',$array1);
            $user_ids = implode(',',$array);
            $where = 'm.userId in ('.$user_ids1.')';
            //隐藏素材集合
    
            $class_id = RecordModel::where('mytask_id',$param['mytask_id'])->value('class_id');
            $data_material_class =  MaterialClassModel::where('user_id','in',$user_ids)->where('class_id',$class_id)->field('material_id')->select();

            $array = [];
            foreach($data_material_class as $key => $value){
                $array[] = $value['material_id'];
            }
            //dump($array);
            if(!empty($array)){
                $material_ids = implode(',',$array);
                $where .= ' and m.id not in ('.$material_ids.')';
            }
         
        }else{
            $where = 'm.userId='.$userId;
        }

        //类型
  
       if($type==0){
           $where.=" and m.content is not null and images is null";
        }elseif($type==1){
           $where.=" and m.images is not null ";
        }elseif($type==2){
            
            $where.=" and m.video is not null";
        }elseif($type==3){
          $where.=" and (m.format=3  or m.format=4)";
        }

        
        $whereOr='';
         $sort = 'm.createTime desc';
        
         

        $data = $Material->getList($where,$whereOr,$sort,$param);
        //halt($data);
       
        foreach ($data as $key => $value) {
            if($value['images'] !=''){
                $data[$key]['imgs'] = explode(',', $value['images']);
            }
            if($value['video'] !=''){
                $data[$key]['videos'] = explode(',', $value['video']);
            }
            if($value['audio'] !=''){
                $data[$key]['audios'] = explode(',', $value['audio']);
            }
            if($value['voice'] !=''){
                $data[$key]['voices'] = explode(',', $value['voice']);
            }
            if($value['rec_time'] !=''){
                $data[$key]['rec_time'] = explode(',', $value['rec_time']);
            }
            $date = substr($value['createTime'], 0,10);

            $time = substr($value['createTime'], -8);

            $city = mb_substr($value['city'],0, mb_strlen($value['city'])-1);
           // var_dump($date);
            $data[$key]['date'] = explode('-',$date);
            $data[$key]['time'] = explode(':',$time);
            $data[$key]['city'] = $city;
            if($value['city'] !=''){
                $data[$key]['adr'] = $city." ".$value['address'];
            }else{
                $data[$key]['adr'] = $value['address'];
            }
            
        }
   
        $this->success('',$data);
    }
    //提审
    public function arraign(){
        $userId       = $this->getUserId();
        $data = $this->request->param();
        $phone=$data['phone'];
        $taskid=$data['taskid'];
        $validate = new Validate([
            'phone'     => 'require',
            'taskid'    => 'require'
        ]);

        $validate->message([
             'phone.require'            => '请输入新手机号!',
             'taskid.require'            => '请输入课程id!',
        ]);
        
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        if (!preg_match('/(^(13\d|15[^4\D]|17[13678]|18\d)\d{8}|170[^346\D]\d{7})$/', $data['phone'])) {
            $this->error("请输入正确的手机格式!");
        }
        $re=Db::name('app_user')->where('phone='.$phone.' and role=2')->find();
       
        if($re){
             $re2=Db::name('anser')->where(['taskid'=>$taskid,'userId'=>$userId])->find();

             if($re2){
                $param['phone']=$data['phone'];
                $param['status']=1;
               $res= Db::name('anser')->where(['taskid'=>$taskid,'userId'=>$userId])->update($param);
             }else{
                $data['createTime']=date('Y-m-d H:i:s',time());
                $data['userId']=$userId;
                $data['status']=1;
                 $res= Db::name('anser')->where(['taskid'=>$taskid,'userId'=>$userId])->insert($data);
             }
          if($res){
            $this->success('提审成功');
          }else{
            $this->error('提审失败');
          }
            
        }else{
             $this->error('老师不存在');
        }
       

    }
    public function class_save(Relation $Relation){
        $userId=$this->getUserId();

        $Id=$this->request->param('taskid');
        $mytask_ids = $Relation->getGrouplist($Id,$userId);

        if($mytask_ids == 0){
            //之前逻辑,防止影响 固保存
            $res= Db::name('anser')->where(['taskid'=>$Id,'userId'=>$userId])->update(['status'=>0]);

            $data=Db::name('mytask')->alias('m')->join('t_template t','m.t_id = t.id')->where('m.id='.$Id)->field('progress')->find();//模板信息
           
            $reply=Db::name('anser')->where(['userId'=>$userId,'taskid'=>$Id])->select()->toArray();

            $reply2=Db::name('anser')->where(['userId'=>$userId,'taskid'=>$Id,'status'=>0])->select()->toArray();
            $cnt = count($reply);
            $cnt2 = count($reply2);

            if($cnt==0){
                //未开始
                $up_data['status'] = 1;
            }elseif ($cnt2 == $data['progress']) {
                //已完成
                $up_data['status'] = 3;
                $up_data['com_time'] = date("Y-m-d H:i:s");
            }else{
                //进行中
                $up_data['status'] = 3;
            }
            Db::name('mytask')->where('id',$Id)->where('uid',$userId)->update($up_data);
        }else{
            foreach ($mytask_ids as $userId => $Id) {
                $res= Db::name('anser')->where(['taskid'=>$Id,'userId'=>$userId])->update(['status'=>0]);

                $data=Db::name('mytask')->alias('m')->join('t_template t','m.t_id = t.id')->where('m.id='.$Id)->field('progress')->find();//模板信息
               
                $reply=Db::name('anser')->where(['userId'=>$userId,'taskid'=>$Id])->select()->toArray();
                $reply2=Db::name('anser')->where(['userId'=>$userId,'taskid'=>$Id,'status'=>0])->select()->toArray();
                $cnt = count($reply);
                $cnt2 = count($reply2);

                if($cnt==0){
                    //未开始
                    $up_data['status'] = 1;
                }elseif ($cnt2 == $data['progress']) {
                    //已完成
                    $up_data['status'] = 3;
                    $up_data['com_time'] = date("Y-m-d H:i:s");
                }else{
                    //进行中
                    $up_data['status'] = 3;
                }
                Db::name('mytask')->where('id',$Id)->where('uid',$userId)->update($up_data);
            }
        }
        
        $this->success('保存成功');
        $this->success('',$status);
    }
    
}
